#include <stdio.h>
#include <stdlib.h>

typedef struct list_node
{
	char*  dataPtr;
	struct list_node*  next;
}ListNode;

typedef struct list
{
	ListNode* head;
	ListNode* tail;
}List;

typedef struct  student
{
	List first;
	int grade;
} Student;

void makeEmptyList(List *lst)
{
	lst->head = lst->tail = NULL;
}

void insertDataToEndList(List *lst, char ch)
{
	ListNode *p;
	if(!lst->head)
	{
		lst->head = malloc(sizeof(ListNode));
		lst->head->next = NULL;
		lst->head->dataPtr = malloc(sizeof(char));
		*(lst->head->dataPtr) = ch;
		return;
	}
	p = lst->head;
	while(p->next)
		p = p->next;
	p->next = malloc(sizeof(ListNode));
	p->next->next = NULL;
	p->next->dataPtr = malloc(sizeof(char));
	*(p->next->dataPtr) = ch;
	lst->tail = p->next;

}

Student unScramble(List lst)
{
	Student ret;
	ListNode *p, *pr, *temp;
	int counter = 10;
	ret.grade = 0;
	p = malloc(sizeof(ListNode));
	p->next = lst.head;
	pr = p;
	/*if((*(p->dataPtr) >= '0') && (*(p->dataPtr) <= '9'))
	{
		ret.grade += *(p->dataPtr) - '0';
		counter *= 10;
		lst.head = p->next;
		free(p);
		p = lst.head;
	}*/
	while(p->next)
	{
		if((*(p->next->dataPtr) >= '0') && (*(p->next->dataPtr) <= '9'))
		{
			ret.grade += counter *(*(p->next->dataPtr) - '0');
			if(counter == 0) ret.grade = 100; //if there are more than 3 digits, 100 is the only options
			counter /= 10;
			temp = p->next->next;
			free(p->next);
			p->next = temp;
			if(p == pr) lst.head = temp;
		}
		p = p->next;
	}
	free(pr);
	p = lst.head;
	while(p->next->next)
		p = p->next;
	if((*(p->next->dataPtr) >= '0') && (*(p->next->dataPtr) <= '9'))
	{
		free(p->next);
		p->next = NULL;
		lst.tail = p;
	}
	ret.first = lst;

	return ret;
}

void printStudent(Student *std)
{
	ListNode *p;
	p = std->first.head;
	printf("First name: ");
	while(p)
	{
		printf("%c", *(p->dataPtr));
		p = p->next;
	}
	printf("\nGrade: %d\n", std->grade);
}

int main()
{
    List lst;
    Student student;
    char ch;

    makeEmptyList(&lst);

    printf("Please enter the scrambled student:\n");

    ch = (char)getchar();
    while(ch != '\n')
    {
        insertDataToEndList(&lst, ch);
        ch = (char)getchar();
    }

    student = unScramble(lst);

    printStudent(&student);

    //freeList(&student.first);
    return 0;
}
